package com.campusbook.controller;

import com.campusbook.model.User;
import com.campusbook.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

/**
 * 用户控制器
 * 演示数据绑定和验证
 */
@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("user") User user, 
                           BindingResult result, 
                           RedirectAttributes redirectAttributes) {
        
        // 验证用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            result.rejectValue("username", "error.user", "用户名已存在");
        }
        
        // 验证邮箱是否已存在
        if (userService.existsByEmail(user.getEmail())) {
            result.rejectValue("email", "error.user", "邮箱已被注册");
        }
        
        if (result.hasErrors()) {
            return "register";
        }
        
        user.setRole("USER");
        user.setStatus(1);
        userService.save(user);
        
        redirectAttributes.addFlashAttribute("successMessage", "注册成功！请登录");
        return "redirect:/login";
    }

    @GetMapping("/profile")
    public String showProfile(Model model) {
        // 获取当前登录用户
        String username = org.springframework.security.core.context.SecurityContextHolder
                .getContext().getAuthentication().getName();
        User user = userService.findByUsername(username);
        model.addAttribute("user", user);
        return "profile";
    }

    @PostMapping("/profile")
    public String updateProfile(@Valid @ModelAttribute("user") User user, 
                              BindingResult result,
                              RedirectAttributes redirectAttributes) {
        
        if (result.hasErrors()) {
            return "profile";
        }
        
        userService.update(user);
        redirectAttributes.addFlashAttribute("successMessage", "个人信息更新成功");
        return "redirect:/users/profile";
    }
}
